<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '选择位置',
    navigationStyle: 'custom',
    disableScroll: true,
    'app-plus': {
      bounce: 'none',
    },
  },
}
</route>

<template>
  <PageLayout navTitle="选择位置" routeMethod="pushTab">
    <map
      id="map"
      style="width: 100%; height: 80%"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :scale="scale"
      @tap="handleMapTap"
      show-location
    ></map>

    <view class="location-controls">
      <wd-button type="primary" @click="confirmLocation">确认位置</wd-button>
      <wd-button @click="getCurrentLocation">我的位置</wd-button>
    </view>

    <view class="address-display">
      <text>{{ currentAddress }}</text>
    </view>
  </PageLayout>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useLocationStore } from '@/store/location'
import { http } from '@/utils/http'
import { userApi } from '@/api/api'

const locationStore = useLocationStore()

const latitude = ref(40.009704)
const longitude = ref(116.374999)
const scale = ref(16)
const currentAddress = ref('请在地图上选择位置')
const markers = reactive([
  {
    id: 0,
    latitude: latitude.value,
    longitude: longitude.value,
    iconPath: '/static/location.png',
    rotate: 0,
    width: 20,
    height: 20,
    title: '选择的位置',
    alpha: 0.8,
    callout: {
      content: '点击地图选择位置',
      color: '#ffffff',
      fontSize: 14,
      borderRadius: 2,
      bgColor: '#00c16f',
      display: 'ALWAYS',
    },
  },
])

onLoad(() => {
  // 从store加载临时位置
  if (locationStore.tempLocation) {
    latitude.value = locationStore.tempLocation.latitude
    longitude.value = locationStore.tempLocation.longitude
    markers[0].latitude = latitude.value
    markers[0].longitude = longitude.value
    currentAddress.value = locationStore.tempLocation.address || '请在地图上选择位置'
  } else {
    getCurrentLocation()
  }
})

// 获取当前位置
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: function (res) {
      latitude.value = res.latitude
      longitude.value = res.longitude
      markers[0].latitude = res.latitude
      markers[0].longitude = res.longitude

      // 获取地址信息
      reverseGeocode(res.latitude, res.longitude)
    },
    fail: function (err) {
      uni.showToast({
        title: '获取位置失败',
        icon: 'none',
      })
      console.error('获取位置失败:', err)
    },
  })
}
// 地图点击时间
const handleMapTap = (e: any) => {
  const { latitude: lat, longitude: lng } = e.detail
  latitude.value = lat
  longitude.value = lng
  markers[0].latitude = lat
  markers[0].longitude = lng

  // 获取点击位置的地址（带防抖）
  debounceReverseGeocode(lat, lng)
}

// 防抖逆地理编码函数
let geocodeTimer: number | null = null
const debounceReverseGeocode = (lat: number, lng: number) => {
  // 清除之前的定时器
  if (geocodeTimer) {
    clearTimeout(geocodeTimer)
  }

  // 设置新的定时器，延迟500毫秒执行
  geocodeTimer = setTimeout(() => {
    reverseGeocode(lat, lng)
  }, 500) as unknown as number
}

// 正在进行的请求标志
let isGeocoding = false
// location.vue 中 reverseGeocode 函数的修改版本
const reverseGeocode = (lat: number, lng: number) => {
  // 如果正在请求，则忽略新请求
  if (isGeocoding) {
    console.log('已有正在进行的逆地理编码请求，忽略此次请求')
    return
  }

  isGeocoding = true
  const addressUrl = userApi.detailAddress + '?latitude=' + lat + '&longitude=' + lng
  // 统一使用后端接口获取地址信息
  http
    .get(addressUrl)
    .then((res: any) => {
      if (res.success) {
        currentAddress.value = res.result.address || `经纬度: ${lat.toFixed(6)}, ${lng.toFixed(6)}`
      } else {
        currentAddress.value = `经纬度: ${lat.toFixed(6)}, ${lng.toFixed(6)}`
      }
    })
    .catch((err) => {
      console.error('逆地理编码失败:', err)
      currentAddress.value = `经纬度: ${lat.toFixed(6)}, ${lng.toFixed(6)}`
    })
    .finally(() => {
      isGeocoding = false
    })
}
// 确认选择的位置
const confirmLocation = () => {
  if (currentAddress.value === '请在地图上选择位置') {
    uni.showToast({
      title: '请先选择位置',
      icon: 'none',
    })
    return
  }

  // 保存到临时位置
  locationStore.setTempLocation({
    latitude: latitude.value,
    longitude: longitude.value,
    address: currentAddress.value,
  })

  // 确认选择
  locationStore.confirmLocation()

  // 返回上一页
  uni.navigateBack()
}

// 初始化时获取当前位置
onMounted(async () => {
  try {
    if (!locationStore.tempLocation) {
      getCurrentLocation()
    }
    await uni.authorize({
      scope: 'scope.userLocation',
      success: () => getCurrentLocation(),
      fail: () => console.log('位置权限被拒绝'),
    })
  } catch (err) {
    console.error('授权失败:', err)
  }
})
</script>

<style lang="scss" scoped>
.location-controls {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background-color: #fff;

  :deep(.wd-button) {
    flex: 1;
    margin: 0 5px;
  }
}

.address-display {
  padding: 10px;
  background-color: #f5f5f5;
  min-height: 40px;
  display: flex;
  align-items: center;

  text {
    font-size: 14px;
    color: #333;
  }
}
</style>
